package com.dongnam.quanly.common.controller;

import org.hibernate.Session;
import org.hibernate.StaleObjectStateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dongnam.quanly.common.dao.ConsoleUserDao;
import com.dongnam.quanly.common.exceptions.DatabaseException;
import com.dongnam.quanly.common.model.ConsoleUser;
import com.dongnam.quanly.common.persistence.HibernateUtil;

public class ConsoleUserController extends GenericController<ConsoleUser, String> {

	private static final Logger logger = LoggerFactory.getLogger(ConsoleUserController.class);

	public ConsoleUserController() {
		super(new ConsoleUserDao());
	}

	@Override
	public ConsoleUserDao getDao() {
		return (ConsoleUserDao) dao;
	}

	public void incrLoginCount(String userId) throws DatabaseException {
		for (int i = 0; i < HibernateUtil.NUM_COMMIT_RETRY; i++) {
			boolean isTransacted = HibernateUtil.getCurrentSession().getTransaction().isActive();
			Session session = isTransacted ? HibernateUtil.getCurrentSession() : HibernateUtil.startCurrentSession();

			try {
				ConsoleUser consoleUser = dao.findById(userId, false);
				consoleUser
						.setLoginFailure((consoleUser.getLoginFailure() == null ? 0 : consoleUser.getLoginFailure()) + 1);
				if (!isTransacted) {
					session.getTransaction().commit();
				}
			} catch (StaleObjectStateException e) {
				rollbackConditionally(isTransacted, session);
				logger.info("incrLoginCount: optimistic lock exception: nAttempt={}", i);
				// do not throw new DatabaseException(e);exception, just do the
				// same thing again
			} catch (Throwable e) {
				rollbackConditionally(isTransacted, session);
				throw new DatabaseException(e);
			}
		}
	}

}
